#!/bin/sh

state=""
oldstate=""
song=""
oldsong=""
while  true ; do
	oldstate=$state
	oldsong=$song
	mpc idle
	string=$(mpc status)
	if [ "$(echo "$string" | wc -l)" -eq 1 ]; then
		if [ "$oldstate" != "stopped"  ]; then
			dunstify -i media-playback-stopped -a mpd -h string:x-dunst-stack-tag:MPD "Stopped" "$oldsong"
		fi
		song=""
		state="stopped"
	elif ! echo "$string" | sed '2!d' | grep -q 'play'; then
		song=$(echo "$string" | sed '1!d')
		if [ "$song" != "$oldsong" ] || [ "$oldstate" != "playing" ]; then
			dunstify -i media-playback-paused -a mpd -h string:x-dunst-stack-tag:MPD "Now Playing:" "$song"
		fi
		state="playing"
	elif ! echo "$string" | sed '2!d' | grep -q 'pause'; then 
		song=$(echo "$string" | sed '1!d')
		if [ "$song" != "$oldsong" ] || [ "$oldstate" != "paused" ]; then
			dunstify -i media-playback-playing -a mpd -h string:x-dunst-stack-tag:MPD "Paused" "$song"
		fi
		state="paused"
	fi
done
